package com.atguigu.yygh.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.repository.ScheduleRepository;
import com.atguigu.yygh.service.IDepartmentService;
import com.atguigu.yygh.service.IHospitalService;
import com.atguigu.yygh.service.IScheduleService;
import com.atguigu.yygh.vo.hosp.BookingScheduleRuleVo;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author kabuda
 * @create 2023-02-27 8:23
 */
@Service
public class ScheduleServiceImpl implements IScheduleService {
    @Resource
    private ScheduleRepository scheduleRepository;
    @Resource
    private MongoTemplate mongoTemplate;

    @Autowired
    private IHospitalService hospitalService;
    @Autowired
    private IDepartmentService departmentService;

    @Override
    public Page<Schedule> getSchedule(String hoscode, Integer page, Integer limit) {
        Schedule schedule = new Schedule();

        schedule.setHoscode(hoscode);
        schedule.setIsDeleted(0);
        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写
        Example example = Example.of(schedule, matcher);
        //mongodb从o页开始计算，所以-1
        Pageable pageable = PageRequest.of(page - 1, limit);

        Page all = scheduleRepository.findAll(example, pageable);
        return all;
    }

    @Override
    public void saveSchedule(Map<String, Object> map) {
        String string = JSON.toJSONString(map);
        Schedule schedule = JSON.parseObject(string, Schedule.class);

        Schedule result = scheduleRepository.getScheduleByHoscodeAndDepcode(schedule.getHoscode(), schedule.getDepcode());

        if (result != null) {
            schedule.setIsDeleted(result.getIsDeleted());
            schedule.setCreateTime(result.getCreateTime());
            schedule.setUpdateTime(new Date());
            schedule.setStatus(result.getStatus());
        } else {
            schedule.setIsDeleted(0);
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            schedule.setStatus(0);
        }

        scheduleRepository.save(schedule);
    }

    @Override
    public void remove(String hosScheduleId) {
        Schedule schedule = scheduleRepository.getScheduleByHosScheduleId(hosScheduleId);
        if (schedule != null) {
            scheduleRepository.delete(schedule);
        }
    }
    //根据医院编号 和 科室编号 ，查询排班规则数据
    @Override
    public Map<String, Object> getScheduleRule(Integer page, Integer limit, String hospcode, String depcode) {
        //1 根据医院编号 和 科室编号 查询
        Criteria criteria = Criteria.where("hoscode").is(hospcode).and("depcode").is(depcode);

        //2 根据工作日workDate期进行分组
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria),//匹配条件
                Aggregation.group("workDate")//分组字段
                        .first("workDate").as("workDate")
                        //3 统计号源数量
                        .count().as("docCount")
                        .sum("reservedNumber").as("reservedNumber")
                        .sum("availableNumber").as("availableNumber"),
                //排序
                Aggregation.sort(Sort.Direction.DESC, "workDate"),
                //4 实现分页
                Aggregation.skip((page - 1) * limit),
                Aggregation.limit(limit)
        );
        //调用方法，最终执行
        AggregationResults<BookingScheduleRuleVo> aggResults =
                mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = aggResults.getMappedResults();

        //分组查询的总记录数
        Aggregation totalAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );
        AggregationResults<BookingScheduleRuleVo> totalAggResults =
                mongoTemplate.aggregate(totalAgg,
                        Schedule.class, BookingScheduleRuleVo.class);
        int total = totalAggResults.getMappedResults().size();

        //把日期对应星期获取
        for (BookingScheduleRuleVo bookingScheduleRuleVo : bookingScheduleRuleVoList) {
            Date workDate = bookingScheduleRuleVo.getWorkDate();
            String dayOfWeek = this.getDayOfWeek(new DateTime(workDate));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
        }

        //设置最终数据，进行返回
        Map<String, Object> result = new HashMap<>();
        result.put("bookingScheduleRuleList", bookingScheduleRuleVoList);
        result.put("total", total);

        //获取医院名称
        Hospital hospital = hospitalService.getHospitalByHoscode(hospcode);
        java.lang.String hosName = hospital.getHosname();
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        baseMap.put("hosname", hosName);
        result.put("baseMap", baseMap);

        return result;
    }

    @Override
    public List<Schedule> getScheduleDetail(String hospcode, String depcode, String workDate) {
        //获取医院名称，科室名称，日期对应星期
        String hosname = hospitalService.getHospitalByHoscode(hospcode).getHosname();
        String depname=departmentService.getDepartmentByCode(hospcode,depcode).getDepname();
        Date date = new DateTime(workDate).toDate();
        //TODO 有问题，查不到数据
        List<Schedule> list=scheduleRepository.findScheduleByHoscodeAndDepcodeAndWorkDate(hospcode,depcode,date);
        list.stream().forEach(item->{
            item.getParam().put("hosname", hosname);
            item.getParam().put("depname", depname);
            item.getParam().put("dayOfWeek", this.getDayOfWeek(new DateTime(item.getWorkTime())));
        });
        return list;
    }

    /**
     * 根据日期获取周几数据
     *
     * @param dateTime
     * @return
     */
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;

    }

}

